<%@ page contentType="text/html;charset=UTF-8" language="java"  import="java.util.*" trimDirectiveWhitespaces="true" %>
<%@include file="/WEB-INF/pages/common/taglib.jsp"%>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>平台商品新增</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <%@include file="/WEB-INF/pages/common/commonCss.jsp"%>

  <link rel="stylesheet" href="${basePath}/resources/css/select2.css" />
  <link rel="stylesheet" href="${basePath}/resources/css/matrix-style.css" />
  <link rel="stylesheet" href="${basePath}/resources/css/matrix-media.css" />
  <link rel="stylesheet" href="${basePath}/resources/css/bootstrap-wysihtml5.css" />
  <link rel="stylesheet" href="${basePath}/resources/css/admin/liandong.css" />




</head>
<style>
  .select2-container {
    float:left;
    width: 35%;
  }
  .controls.marb5 img{
    margin-bottom:5px;
  }
  label {
    display: inline-block;
    padding-right: 1rem;
  }
  .text-min{
     width: 56px;
  }
  ul li{

  }
</style>
<body>

<!--Header-part-->
<%@include file="/WEB-INF/pages/common/head.jsp"%>


<!--sidebar-menu-->
<%@include file="/WEB-INF/pages/common/left.jsp"%>

<div id="content">
  <div id="content-header">
    <div id="breadcrumb"> <a href="#" title="Go to Home" class="tip-bottom"><i class="icon-home"></i> </a>
      <a href="#" class="current">平台商品新增</a> </div>
    <%--<h1>平台商品新增</h1>--%>
  </div>

  <div class="container-fluid">

    <div class="row-fluid">
      <div class="span12">
        <div class="widget-box">
          <div class="widget-title"> <span class="icon"> <i class="icon-align-justify"></i> </span>
            <h5></h5>
          </div>
          <div class="widget-content nopadding">
            <form action="${adminPath}/shop/good/save"  id="form"  method="POST" class="form-horizontal" >
              <input type="file" class="hidden" id="file" name="file"  accept="image/jpeg,image/png,image/gif,audio/mp3"  onchange="uploadFile()" />


              <div class="control-group">
                <label class="control-label chooseCatogory">
                  选择分类
                </label>
                <div class="controls">
                   <a class="btn btn-success"  data-opid="${good.id}" onclick="good.getAllcatogories(this)">选择</a>
                </div>
              </div>


              <div id="p_colorCode" style="background:#fff2db;padding-bottom: 20px;">
                <div class="control-group">
                  <label class="control-label">添加自定义规格</label>
                  <div class="controls">
                    <select onchange="good.checkAtrr(this)">
                      <option value="">请选择</option>
                      <option value="material$材质$K金">材质</option>
                      <option value="color$颜色$黄">颜色</option>
                      <option value="mainStoreSpec$主石规格$0.100ct">主石规格</option>
                      <option value="handSize$戒指手寸$18寸">戒指手寸</option>
                      <option value="necklace_len$项链长度$42cm">项链长度</option>
                      <option value="bracelet_len$手链长度$16cm">手链长度</option>
                    </select>
                  </div>
                </div>

                <div class="control-group">
                  <label class="control-label">产品规格</label>
                  <div class="controls">
                    <div id="navtab1" style="width: 100%;border:1px solid #A3C0E8;">
                      <div  tabid="tabItem3">
                        <div id="Div1">
                          <div position="center">
                            <div style="padding: 5px 8px;" class="div_content">
                              <div class="div_title"><span></span></div>
                              <div class="div_contentlist">
                                <%--<ul class="Father_Title"><li>颜色</li></ul>--%>
                                <%--<ul class="Father_Item0">--%>
                                  <%--<li class="li_width">--%>
                                    <%--&lt;%&ndash;<label><input id="Checkbox3" type="checkbox" class="chcBox_Width" value="黄色" /><span class="li_empty"  contentEditable="true" style="border:1px solid #666;padding: 0.5rem;">黄色</span>&ndash;%&gt;--%>
                                    <%--&lt;%&ndash;</label>&ndash;%&gt;--%>
                                    <%--<input  id="Checkbox1" type="checkbox" class="chcBox_Width"  value="黄" >--%>
                                    <%--<label class="labelname" title="黄" onclick="good.changshow(this,'color')" >黄</label>--%>
                                    <%--<input  type="text" style="display: none;" maxlength="10" name="color" class="text text-min data-value" onchange="good.changeCheckVal(this)" value="" >--%>
                                  <%--</li>--%>
                                <%--</ul>--%>
                                <%--<div style="clear: both"></div>--%>
                                <%--<br />--%>
                                <ul class="Father_Title"><li>重量</li></ul>
                                <ul class="Father_Item0">
                                  <li class="li_width">
                                    <input id="Checkbox1" type="checkbox"  class="chcBox_Width" value="4.0g" >
                                    <label class="labelname" title="4.0g" onclick="good.changshow(this,'weight')" >4.0g</label>
                                    <input  type="text" style="display: none;" maxlength="10"  class="text text-min data-value" onchange="good.changeCheckVal(this)" value="" >
                                  </li>
                                </ul>
                                <div style="clear: both"></div>


                              </div>
                              <div class="div_contentlist2">
                                <ul>
                                  <li><div id="createTable"></div></li>
                                </ul>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

              </div>


              <div class="control-group">
                <label class="control-label">商品编号 :</label>
                <div class="controls">
                  <input type="text" class="span5" id="goodno" name="goodno" placeholder="商品编号"  id="goodno" >
                </div>
              </div>


              <div class="control-group">
                <label class="control-label">商品标题 :</label>
                <div class="controls">
                  <input type="text" class="span8" id="title" name="title" placeholder="商品标题"  id="title" maxlength="30" onkeyup="good.tongjiWord(this,30)">
                  <span class="word"><b>0</b>/30</span>
                </div>
              </div>



              <div class="control-group">
                <label class="control-label">主图(860*860):</label>
                <div class="controls">
                  <input type="hidden" name="bannerurl" id="bannerurl">
                  <img  data-img="${good.bannerurl}" onclick="openBrowse(this,0)" data-dir="good/images" src="${basePath}/resources/images/noimage.gif" alt="" width="300" height="300">
                </div>
              </div>

              <div class="control-group">
                <label class="control-label">推荐图(720*406):</label>
                <div class="controls">
                  <input type="hidden" name="hotimgurl" id="hotimgurl">
                  <img  data-img="${good.bannerurl}" onclick="openBrowse(this,2)" data-dir="good/images" src="${basePath}/resources/images/noimage.gif" alt="" width="180" height="101">
                </div>
              </div>



              <div class="control-group">
                <label class="control-label">

                  详情轮播图(860*860):
                  <label class="control-label">
                    最多5张
                    <i class="icon-plus" style="margin-right: 1rem" onclick="good.addPicture()"></i>
                  </label>
                </label>
                <div class="controls marb5" >
                  <input type="hidden" name="detailimgurl">
                  <img  data-img="${good.bannerurl}" onclick="openBrowse(this,1)" data-dir="good/images" src="${basePath}/resources/images/noimage.gif" alt="" width="150" height="150px">
                </div>
              </div>

               <%@include file="filed.jsp"%>


              <div class="control-group">
                <label class="control-label">是否推荐</label>
                <div class="controls">
                  <label>
                    <input type="radio" value="001" name="ishotCode"  checked="checked"> 是
                  </label>
                  <label>
                    <input type="radio" value="002" name="ishotCode" > 否
                  </label>
                </div>
              </div>

              <div class="control-group">
                <label class="control-label">是否显示</label>
                <div class="controls">
                  <label>
                   <input type="radio" value="001" name="showCode" checked="checked">  显示
                  </label>
                  <label>
                    <input type="radio" value="002" name="showCode" > 不显示
                  </label>
                </div>
              </div>

              <div class="control-group">
                <label class="control-label">是否可换</label>
                <div class="controls">
                  <label>
                    <input type="radio" value="0" name="canchange"  > 可换
                  </label>
                  <label>
                    <input type="radio" value="1" name="canchange" checked="checked"> 不可换
                  </label>
                </div>
              </div>

              <div class="control-group">
                <label class="control-label">商品描述</label>
                <div class="controls">
                    <textarea id="editor_id"  class="span10"  name="description" style="width:90%;height:300px;" ></textarea>
                </div>
              </div>


              <div class="form-actions">
                <div class="control-group">
                  <div class="controls">
                    <button type="button" onclick="good.submit()" class="btn btn-success">保存</button>
                    <button type="reset" class="btn btn-default"  onclick="history.go(-1)">返回</button>
                  </div>
                </div>
              </div>

          </form>
          </div>

          </div>
        </div>
      </div>
    </div>
  </div>


  <!-- Modal -->

</div>



<!--Footer-part-->
<%@include file="/WEB-INF/pages/common/footer.jsp"%>

<!--end-Footer-part-->

<%@include file="/WEB-INF/pages/common/commonJS.jsp"%>
<script src="${basePath}/resources/js/bootstrap.min.js"></script>
<script src="${basePath}/resources/js/kindeditor-4.1.10/kindeditor.js"></script>
<script src="${basePath}/resources/js/kindeditor-4.1.10/lang/zh_CN.js"></script>
<script src="${basePath}/resources/js/kindeditor-4.1.10/plugins/code/prettify.js"></script>
<script type="text/javascript" src="${basePath}/resources/js/upload/upload.js"></script>
<script type="text/javascript" src="${basePath}/resources/js/admin/liandong.js"></script>


<script>

  KindEditor.ready(function(K) {
    K.create('#editor_id', {
      uploadJson : basePath+'/kindEditor/fileUpload',
      fileManagerJson : basePath+'/kindEditor/fileManager',
      allowFileManager : true ,
      afterCreate : function() {
        var self = this;
        K.ctrl(document, 13, function() {
          self.sync();
          document.forms['example'].submit();
        });
        K.ctrl(self.edit.doc, 13, function() {
          self.sync();
          document.forms['example'].submit();
        });
      },
        //下面这行代码就是关键的所在，当失去焦点时执行 this.sync();
        afterBlur: function(){this.sync();}
    });
    prettyPrint();
  })


  var good = {
        submit:function () {

            if(!localStorage.getItem('hfl_catogories')){
                loading('请选择分类',5);
                $('html,body').animate({scrollTop: '0px'}, 1000);
                return;
            }
            //验证规格价格和库存以及存放规格价格和库存
            var mark = good.validateGoodChild();
            if(!mark){
                $('html,body').animate({scrollTop: '50px'}, 1000);
                return;
            }
            //拼接商品子表字段
            var goodChildAttr = good.concatGoodChild();
            console.log('goodchild=='+JSON.stringify({goodchild:JSON.stringify(goodChildAttr)}));
            //拼接分类集合字段
            var CatogoryArr = localStorage.getItem('hfl_catogories').split(",");
            var CatogoryAtrStr =  good.concatCatogory(CatogoryArr);

            var edtior = $("#editor_id").val();
            var title = $('#title').val();
            var goodno = $('#goodno').val();
            var shortinfo =  $('#shortinfo').val();
            var oldprice =  $('#oldprice').val();
            var position =  $('#position').val();
            var stocknum =  $('#stocknum').val();

            var mark = false; //图片标示

            $("img").each(function(){
                var $this = $(this);
                console.log($this.attr('src'));
                if ($this.attr('src')=='' || ($this.attr('src').indexOf('resources/images/noimage.gif')!=-1)) {
                    mark = true;
                }
            });
            if(isEmpty(goodno)){
                loading("请输入商品编号",4);
                $("#goodno").focus();
                return;
            }
            if(isEmpty(title)){
                loading("请输入商品标题",4);
                $("#title").focus();
                return;
            }
            if(mark){
                $('html,body').animate({scrollTop: '300px'}, 1000);
                loading("还有未上传的图片",4);
                 return;
            }

            if(isEmpty(shortinfo)){
                loading("请输入商品简介",4);
                $("#shortinfo").focus();
                return;
            }

            if(isEmpty(oldprice)){
                loading("请输入原价格",4);
                $('#oldprice').focus();
                return;
            }

            if(isEmpty(stocknum)){
                loading("库存总数不能为空",4);
                $("#stocknum").focus();
                return;
            }
            if(isEmpty(position)){
                loading("顺序号不能为空",4);
                $("#position").focus();
                return;
            }

            if(isEmpty(edtior)){
                loading("商品详情不能为空",4);
                return;
            }
            //拼接商品子表字段
            var goodChildAttr = good.concatGoodChild();
            data = $.param({goodchild:JSON.stringify(goodChildAttr)}) +'&' + CatogoryAtrStr+ $('#form').serialize();

            $.ajax({
                url:adminPath+'/shop/good/saveGood',
                type:'post',
                data:data,
                success:function (data) {
                    console.log(JSON.stringify(data));
                    loading("恭喜发布商品成功",3);
                    window.location.href =  adminPath +"/shop/good/list";
                }
            });

        },
       check:function (obj) {
          var reg = /^\d+\.?(\d{1,2})?$/;
          var val = $(obj).val();
          if(!reg.test(val)){
              $(obj).val("");
              $(obj).focus();
          }
        },
        //组装goodchild人数据
        validateGoodChild:function(){
           var mark = true;//goodchild组装完整性 表示，false表示规格数据不完整，true表示规格数据完整
           if(recordArr.length==0 || !recordArr){
               loading('产品规格没有选择',5);
               mark = false;
           }else{
               //组装goodchilren数据
               $("input[name='Txt_PriceSon']").each(function (i,item) {
                   var price = $(this).val();
                   if(!price){
                       loading("规格价格填写不完整",5);
                       mark =false;
                   }else{
                       $.each(recordArr, function (index, item) {
                           if(index == i){
                               item.push(price);
                           }
                       });
                   }
               })
               //组装goodchilren数据
               $("input[name='Txt_exSon']").each(function (i,item) {
                   var exprice = $(this).val();
                   if(!exprice){
                       loading("换款价格填写不完整",5);
                       mark =false;
                   }else{
                       $.each(recordArr, function (index, item) {
                           if(index == i){
                               item.push(exprice);
                           }
                       });
                   }
               })
               $("input[name='Txt_CountSon']").each(function ( j ,item) {
                   var count = $(this).val();
                   if(!count){
                       loading("规格库存数量填写不完整",5);
                       mark =false;
                   }else{
                       $.each(recordArr, function (index, item) {
                           if(index == j ){
                               item.push(count);
                           }
                       });
                   }
               })
           }
           return  mark;

        },
        //拼接商品子类的字符串
        concatGoodChild:function () {
            var goodChildAttr = [];
            console.log('recordArr=='+JSON.stringify(recordArr));
            for(var i=0,len=recordArr.length;i<len;i++){
               var eachArr = recordArr[i];//每行的记录数
                var obj = {};//每一行的对象
                eachArr = eachArr.join(",").split(",");
                var AtrrTitleAttr = good.getAtrrTitle(); //第一行标题名字数组
                for(var j=0,llen=eachArr.length;j<llen;j++){
                    var title= AtrrTitleAttr[j];
                    console.log('eachArr[j]=='+eachArr[j]);
                    obj[title] = eachArr[j];
                }
                goodChildAttr.push(obj);
            }
            return goodChildAttr;
        },
        //拼接分类字符串
        concatCatogory:function (CatogoryArr) {
            var CatogoryAtrStr = '';
            for(var i=0,len=CatogoryArr.length;i<len;i++){
               var str = CatogoryArr[i];
               var catogoryObj = {catogoryId:str};
               CatogoryAtrStr += $.param(catogoryObj) + '&';
            }
            return  CatogoryAtrStr;
        },
        //获取规格属性列表
        getAtrrTitle:function () {
            var TitleArr = [];
            //获取规格列表
            $('table th').each(function (index , item) {
                TitleArr.push(good.diyTitle[$(this).html()]);
            })
            return TitleArr;
        },
        //新增
        save:function(){
        },
        //新增颜色
        addColor:function(){
            $("#p_colorCode").append("<div class='control-group'>"+
                "  <label class='control-label'>"+
                "	<i class='icon-plus' style='margin-right: 1rem' onclick='good.addColor()'></i>颜色 :"+
                "  </label>"+
                "  <div class='controls'>"+
                "	<input type='text' class='span2 childColor'   name='color' placeholder='颜色'>"+
                "  </div>"+
                "</div> "+
                "<div class='control-group'>"+
                "  <label class='control-label'>数量:</label>"+
                "  <div class='controls'>"+
                "	  <input type='number' name='stocknumber' onblur='good.addstocknum(this)'   placeholder='所选数量'  class='span2 stocknumber childStocknumber'>"+
                "  </div>"+
                "</div>  "+
                "<div class='control-group' >"+
                "  <label class='control-label'>该颜色图(720*480)</label>"+
                "  <input type='hidden' name='imgurl' >"+
                "  <div class='controls'>"+
                "<img  data-img='' onclick='openBrowse(this,0)' data-dir='good/images' src='xxx' alt=''>" +
                "</div>");
            imgerr.init();
        },
        addstocknum:function(obj){
          var totalnum =   0;
          $(".stocknumber").each(function(index){
            var num =0;
            if($(this).val()){
              num =   $(this).val()*1;
              totalnum=totalnum*1 + num;
            }
          });
          $("#stocknum").val(totalnum);
        },
        getSecondCatagory:function(){
            var firstcatogory = $("#firstcatogory").val();
            if(this.value==""){
                $("#categoryId").val("");
            }
            if(!firstcatogory){
               return;
            }
            good.getHttpSecond(firstcatogory);
        },
        //获得二级分类的数据
        getHttpSecond:function (firstcatogory) {
            $.ajax({
                type:'post',
                url:basePath+'/admin/shop/good/getSecondCatogory',
                data:{pid:firstcatogory},
                success:function(data){
                    var html = "";
                    for(var i= 0,len=data.length;i<len;i++){
                        html+="<option value='"+data[i].id+"'>"+data[i].name+"</option>";
                    }
                    //console.log(html);
                    $("#categoryId").html(html);
                },
                error:function(err){
                    console.log(err);
                }
            });
        },
        markHtml:{}, //复选框切换的checkbox复制框
        diyAttr:{"material":"K金","mainStoreSpec":"0.235ct","handSize":"16寸","necklace_len":"40cm","bracelet_len":"14cm"},
        diyTitle:{"颜色":"color","重量":"weight","材质":"material","主石规格":"mainstorespec",
            "戒指手寸":"handsize","项链长度":"necklaceLen","手链长度":"braceletLen","价格(元)":"price","换款价(元)":"exprice","库存(件)":"stocknumber"},
        //文本框切换
        changshow:function (obj,mark) {
            var $this= $(obj);
            var mark = mark+'ParentHtml';
            console.log(mark);
            if(!good.markHtml[mark])good.markHtml[mark] = $this.parent().html();
            $this.hide();
            $this.prev().attr({'checked':true});
            $this.next().val($this.html()).show();
            $this.parent().append(good.markHtml[mark]);
            var checkboxIndex = $(".div_contentlist .li_width").children().length+1;
            console.log($this.parent().find("input[type='checkbox']:last-child"));
            $this.parent().find("input[type='checkbox']:last-child").attr("id",checkboxIndex);
            step.Creat_Table();
            $(".div_contentlist input[type='checkbox']").bind("change", function () {
                console.log(111);
                step.Creat_Table();
            });

        },
        //下拉自定义属性
        checkAtrr:function(obj){
            var $this = $(obj);
            var val = $this.val();
            if(val){
                var arr = val.split('$');
                 console.log(arr);
                var mark = false;
                var thisIndex = 0;
                $(".Father_Title li").each(function (index,item) {
                    //console.log(index + "==="+$(this).html());
                    var html = $(this).html();
                    thisIndex = index+1;
                     //console.log(html + '==ss=' + arr[1]);
                    if(html == (arr[1])) mark= true;
                })
                if(mark) return;
                var checkboxIndex = $(".div_contentlist .li_width").children().length+1;
                $(".div_contentlist").append(
                    "<br />"+
                    "<ul class='Father_Title'><li>"+arr[1]+"</li></ul>"+
                    "<ul class='Father_Item"+thisIndex+"'>"+
                    "  <li class='li_width'>"+
                    "	<input id='Checkbox2' type='checkbox'  class='chcBox_Width' value='"+arr[2]+"' >"+
                    "	<label class='labelname' title='4.0g' onclick='good.changshow(this,\""+arr[0]+"\")' >"+arr[2]+"</label>"+
                    "	<input  type='text' style='display: none;' maxlength='10'  class='text text-min data-value' onchange='good.changeCheckVal(this)' value='' >"+
                    "  </li>                                  "+
                    "</ul>"+
                    "<div style='clear: both'></div>");

                $(".div_contentlist input[type='checkbox']").bind("change", function () {
                    step.Creat_Table();
                });
            }
        },
        //产品规格选择的时候 更变规规格值 的时候 触发的事件
        changeCheckVal:function (obj) {
            var $this = $(obj);
            if(!$this.val()){
                loading("值不能为空",3);
                $this.focus();
                return;
            }
            $this.prev().prev().val($this.val());
            step.Creat_Table();
            $(".div_contentlist input[type='checkbox']").bind("change", function () {
                console.log(111);
                step.Creat_Table();
            });
        },
       //选择产品分类
        getAllcatogories:function(obj){
            var $obj = $(obj);
            var opid = $obj.data("opid");
            $.tzIframe({width:420,height:400,title:"选择商品分类",draggle:false,content:adminPath+"/shop/good/getAllcatogories?opid="+opid,callback:function(iframe,$dialog,opts){
                if(iframe){
                    iframe.saveCatogory(opid,$dialog,opts);
                }
            },loadSuccess:function(iframe){
                iframe.initCatogoryTree(function(){
                    //选中已经选择的分类
                      iframe.getChecked(opid);
                }
                );
            }});
        },
        //商品标题统计个数
        tongjiWord:function (obj,num) {
            var word = $(obj).val()
            if(word){
                $(".word b").html(word.length>num?num:word.length);
            }else{
                $(".word b").html(0);
            }
        },
        //修改库存数量
        changeStockNum:function() {
            var total = 0;//库存总数
           $("input[name='Txt_CountSon']").each(function (obj) {
                 var num = $(this).val();
                 if(num) total += parseInt(num);
           })
           $("input[name='stocknum']").val(total);
       },
        lunboImgCount:1,
        //添加轮播图
        addPicture:function () {
            good.lunboImgCount++;
            if(good.lunboImgCount>5){
                loading("最多上传5张奥",4);
                return;
            }
            $('.marb5').append("<input type='hidden' name='detailimgurl'>"+
                "<img  data-img='${good.bannerurl}' onclick='openBrowse(this,1)' data-dir='good/images' src='${basePath}/resources/images/noimage.gif' alt='' width='150' height='150'>");
            $('.marb5 img').css({marginRight:5});

        }
  };





  function tz_uploadsuccess(jdata ,obj) {
      if (jdata.target ==0) {
          console.log(JSON.stringify(jdata.name) );
          $(obj).attr("src", basePath + "/" + jdata.url + "?" + new Date().getTime()).css({width:300,height:300});
          $(obj).prev().val(JSON.stringify(jdata.name));
//          $("#bannerurl").val(JSON.stringify(jdata.name));
       }else if (jdata.target ==1) {
          console.log(JSON.stringify(jdata.name) );
          $(obj).attr("src", basePath + "/" + jdata.url + "?" + new Date().getTime()).css({width:150,height:150});
          $(obj).prev().val(JSON.stringify(jdata.name));
//          $("#bannerurl").val(JSON.stringify(jdata.name));
      }else if (jdata.target ==2) {
          console.log(JSON.stringify(jdata.name) );
          $(obj).attr("src", basePath + "/" + jdata.url + "?" + new Date().getTime()).css({width:180,height:101});
          $(obj).prev().val(JSON.stringify(jdata.name));
    //          $("#bannerurl").val(JSON.stringify(jdata.name));
       }
      else if (jdata.target == "#audio") {
          $(jdata.target).attr("src", basePath + "/" + jdata.url).data("link", jdata.url);
          $("#musictitle").val(jdata.name);
          $("#musicsize").val(jdata.size);
          $("#musiclink").val(jdata.url);
          adminBlog.audioDom.oncanplaythrough = function () {
              var time = this.duration;
              var m = Math.ceil(time / 60);
              var s = Math.ceil(time % 60);
              if (m < 10) m = "0" + m;
              if (s < 10) s = "0" + s;
              $("#musictime").val(m + ":" + s);
          }
      }
  }

  $(function () {
      imgerr.init();
      good.getHttpSecond(1);;
  })
</script>

</body>
</html>
